package com.aabte.lock.jedis.v1;

import redis.clients.jedis.Jedis;

import java.util.Collections;

public class RedisPessimisticLock {

    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final String RELEASE_SUCCESS = "1";
    private static final String SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    private Jedis jedis;
    private String lockKey;
    private String lockValue;
    private long expireTime;

    public RedisPessimisticLock(Jedis jedis, String lockKey, String lockValue, long expireTime) {
        this.jedis = jedis;
        this.lockKey = lockKey;
        this.lockValue = lockValue;
        this.expireTime = expireTime;
    }

    /**
     * 尝试获取分布式锁
     * @return 是否获取成功
     */
    public boolean tryGetDistributedLock() {
        String result = jedis.set(lockKey, lockValue, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
        return LOCK_SUCCESS.equals(result);
    }

    /**
     * 释放分布式锁
     * @return 是否释放成功
     */
    public  boolean releaseDistributedLock() {
        Object result = jedis.eval(SCRIPT, Collections.singletonList(lockKey), Collections.singletonList(lockValue));
        return RELEASE_SUCCESS.equals(result);
    }

}
